<?php

namespace app\api\services\admin\log;

use app\api\common\service\BaseServices;
use app\api\common\traits\ServicesTrait;
use app\api\dao\admin\log\SystemLogDao;

/**
 * 系统日志
 *
 * @author GQL
 * @since  1.0
 */
class SystemLogServices extends BaseServices
{
    use ServicesTrait;

    /**
     * 构造方法
     * SystemLogServices constructor.
     *
     * @param SystemLogDao $dao
     */
    public function __construct(SystemLogDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 记录访问日志
     *
     * @param int|string  $adminId
     * @param string|null $adminName
     * @param string|null $type
     *
     * @return bool
     */
    public function recordAdminLog(int|string $adminId, null|string $adminName, null|string $type): bool
    {
        $request = app()->request;
        $path    = trim(strtolower($request->pathinfo()));
//        $rule = trim(strtolower($request->rule()->getRule()));

        /** @var SystemMenusServices $service */
        //$service = app()->make(SystemMenusServices::class);
        $data = [
            'method'     => $request->method(),
            'admin_id'   => $adminId,
            'add_time'   => time(),
            'admin_name' => $adminName,
            'path'       => $path,
            //'page' => $service->getVisitName($rule) ?: '未知',
            'ip'         => $request->ip(),
            'type'       => $type,
            'agent'      => $request->server('HTTP_USER_AGENT'),
            'params'     => json_encode($request->all()),
        ];
        if ($this->dao->save($data)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取系统日志列表
     *
     * @param array $where
     * @param int   $level
     *
     * @return array
     */
    public function getLogList(array $where, int $level): array
    {
        [$page, $limit] = $this->getPageValue();
//        if (!$where['admin_id']) {
//            /** @var SystemAdminServices $service */
//            $service           = app()->make(SystemAdminServices::class);
//            $where['admin_id'] = $service->getAdminIds($level);
//        }
        $list  = $this->dao->getLogList($where, $page, $limit);
        $count = $this->dao->count($where);
        return compact('list', 'count');
    }
}
